package com.dhcc.core.framework.xss;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
 * XSS过滤处理
 * 
 * @ClassName: XssHttpServletRequestWrapper
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:39:48
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    // 没被包装过的HttpServletRequest（特殊场景，需要自己过滤）
    HttpServletRequest orgRequest;

    // html过滤
    private static HTMLFilter htmlFilter;

    static{
        Map<String, Object> conf = new HashMap<>();
        Map<String, List<String>> vAllowed = new HashMap<>();

        final ArrayList<String> a_atts = new ArrayList<String>();
        a_atts.add("id");
        a_atts.add("name");
        a_atts.add("class");
        a_atts.add("href");
        a_atts.add("target");
        a_atts.add("title");
        a_atts.add("style");
        vAllowed.put("a", a_atts);

        final ArrayList<String> img_atts = new ArrayList<String>();
        img_atts.add("id");
        img_atts.add("name");
        img_atts.add("class");
        img_atts.add("src");
        img_atts.add("width");
        img_atts.add("height");
        img_atts.add("alt");
        img_atts.add("title");
        img_atts.add("style");
        vAllowed.put("img", img_atts);

        final ArrayList<String> common_atts = new ArrayList<String>();
        common_atts.add("style");
        common_atts.add("title");
        common_atts.add("id");
        common_atts.add("name");
        common_atts.add("class");

        vAllowed.put("b", common_atts);
        vAllowed.put("blockquote", common_atts);
        vAllowed.put("br", common_atts);
        vAllowed.put("caption", common_atts);
        vAllowed.put("cite", common_atts);
        vAllowed.put("code", common_atts);
        vAllowed.put("col", common_atts);
        vAllowed.put("colgroup", common_atts);
        vAllowed.put("dd", common_atts);
        vAllowed.put("div", common_atts);
        vAllowed.put("dl", common_atts);
        vAllowed.put("dt", common_atts);
        vAllowed.put("em", common_atts);
        vAllowed.put("h1", common_atts);
        vAllowed.put("h2", common_atts);
        vAllowed.put("h3", common_atts);
        vAllowed.put("h4", common_atts);
        vAllowed.put("h5", common_atts);
        vAllowed.put("h6", common_atts);
        vAllowed.put("i", common_atts);
        vAllowed.put("li", common_atts);
        vAllowed.put("ol", common_atts);
        vAllowed.put("p", common_atts);
        vAllowed.put("pre", common_atts);
        vAllowed.put("q", common_atts);
        vAllowed.put("small", common_atts);
        vAllowed.put("span", common_atts);
        vAllowed.put("strike", common_atts);
        vAllowed.put("strong", common_atts);
        vAllowed.put("sub", common_atts);
        vAllowed.put("sup", common_atts);
        vAllowed.put("u", common_atts);
        vAllowed.put("ul", common_atts);
        
        final ArrayList<String> table_atts = new ArrayList<String>();
        table_atts.add("id");
        table_atts.add("name");
        table_atts.add("style");
        table_atts.add("class");
        table_atts.add("border");
        table_atts.add("cellpadding");
        table_atts.add("cellspacing");
        table_atts.add("width");
        table_atts.add("height");
        table_atts.add("title");
        table_atts.add("valign");
        table_atts.add("align");
        table_atts.add("colspan");
        table_atts.add("rowspan");
        table_atts.add("bgcolor");

        vAllowed.put("table", table_atts);
        vAllowed.put("tbody", table_atts);
        vAllowed.put("td", table_atts);
        vAllowed.put("tfoot", table_atts);
        vAllowed.put("th", table_atts);
        vAllowed.put("thead", table_atts);
        vAllowed.put("tr", table_atts);

        conf.put("vAllowed", vAllowed);

        String[] vSelfClosingTags = new String[] { "img" };
        conf.put("vSelfClosingTags", vSelfClosingTags);

        String[] vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };
        conf.put("vNeedClosingTags", vNeedClosingTags);

        String[] vDisallowed = new String[] {};
        conf.put("vDisallowed", vDisallowed);

        String[] vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp.
        conf.put("vAllowedProtocols", vAllowedProtocols);

        String[] vProtocolAtts = new String[] { "src", "href" };
        conf.put("vProtocolAtts", vProtocolAtts);

        String[] vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };
        conf.put("vRemoveBlanks", vRemoveBlanks);

        String[] vAllowedEntities = new String[] { "amp", "gt", "lt", "quot", "nbsp"};
        conf.put("vAllowedEntities", vAllowedEntities);

        Boolean stripComment = true;
        conf.put("stripComment", stripComment);

        Boolean encodeQuotes = false;
        conf.put("encodeQuotes", encodeQuotes);

        Boolean alwaysMakeTags = false;//自动补全  修改为false  form表单中 > < ≥ ≤可以原样保存到数据库中
        conf.put("alwaysMakeTags", alwaysMakeTags);

        htmlFilter = new HTMLFilter(conf);
    }

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest = request;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 非json类型，直接返回
        String header_content_type = super.getHeader(HttpHeaders.CONTENT_TYPE);
        if (header_content_type == null || (!header_content_type.equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE))) {
            return super.getInputStream();
        }

        // 为空，直接返回
        String json = IOUtils.toString(super.getInputStream(), "utf-8");
        if (StringUtils.isBlank(json)) {
            return super.getInputStream();
        }

        // xss过滤
        json = xssEncode(json);
        final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bis.read();
            }
        };
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters == null || parameters.length == 0) {
            return null;
        }

        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = xssEncode(parameters[i]);
        }
        return parameters;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> map = new LinkedHashMap<>();
        Map<String, String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = xssEncode(values[i]);
            }
            map.put(key, values);
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    private String xssEncode(String input) {
        return htmlFilter.filter(input);
    }

    /**
     * 获取最原始的request
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
        if (request instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) request).getOrgRequest();
        }

        return request;
    }

}
